package com.qyhl.webtv.module_microvideo.shortvideo;

import android.Manifest;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.RelativeLayout;

import androidx.annotation.Nullable;
import androidx.core.view.ViewCompat;
import androidx.core.view.ViewPropertyAnimatorListener;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentPagerAdapter;
import androidx.viewpager.widget.ViewPager;

import com.alibaba.android.arouter.facade.annotation.Autowired;
import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.android.arouter.launcher.ARouter;
import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;
import com.flyco.tablayout.SlidingTabLayout;
import com.google.gson.Gson;
import com.gyf.immersionbar.ImmersionBar;
import com.makeramen.roundedimageview.RoundedImageView;
import com.orhanobut.hawk.Hawk;
import com.qyhl.webtv.basiclib.base.BaseActivity;
import com.qyhl.webtv.basiclib.base.BaseIViewPresenter;
import com.qyhl.webtv.basiclib.utils.MPermissionUtils;
import com.qyhl.webtv.basiclib.utils.StringUtils;
import com.qyhl.webtv.basiclib.utils.network.EasyHttp;
import com.qyhl.webtv.basiclib.utils.network.callback.SimpleCallBack;
import com.qyhl.webtv.basiclib.utils.network.exception.ApiException;
import com.qyhl.webtv.basiclib.utils.network.model.ApiResult;
import com.qyhl.webtv.commonlib.common.CommonUtils;
import com.qyhl.webtv.commonlib.constant.ARouterPathConstant;
import com.qyhl.webtv.commonlib.constant.AppConfigConstant;
import com.qyhl.webtv.commonlib.service.UserService;
import com.qyhl.webtv.commonlib.utils.eventbus.BusFactory;
import com.qyhl.webtv.commonlib.utils.eventbus.Event;
import com.qyhl.webtv.commonlib.utils.router.RouterManager;
import com.qyhl.webtv.module_microvideo.R;
import com.qyhl.webtv.module_microvideo.R2;
import com.qyhl.webtv.module_microvideo.common.VideoUrl;
import com.qyhl.webtv.module_microvideo.shortvideo.home.ShortVideoHomeFragment;
import com.qyhl.webtv.module_microvideo.shortvideo.introduction.ShortVideoIntroductionFragment;
import com.qyhl.webtv.module_microvideo.shortvideo.rank.ShortVideoRankFragment;
import com.qyhl.webtv.module_microvideo.shortvideo.theme.ShortVideoThemeFragment;
import com.umeng.socialize.UMShareAPI;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import es.dmoral.toasty.Toasty;

/**
 * 孔子到家首页
 */
@Route(path = ARouterPathConstant.SHORT_VIDEO_MAIN)
public class ShortVideoActivity extends BaseActivity {
    @BindView(R2.id.user_avatar)
    RoundedImageView userAvatar;
    @BindView(R2.id.tabLayout)
    SlidingTabLayout tabLayout;
    @BindView(R2.id.view_pager)
    ViewPager viewPager;
    @BindView(R2.id.bottom_bar)
    RelativeLayout bottomBar;

    @Autowired(name = "id")
    String activityId;

    private BottomBarStatus bottomBarStatus = BottomBarStatus.EXPAND;

    boolean isRunning = false;

    private enum BottomBarStatus {
        EXPAND,
        COLLAPSED
    }


    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

    }


    @Override
    protected int getContentView() {
        return R.layout.micro_activity_short_video;
    }

    @Override
    protected void setImmersionBar(ImmersionBar mImmersionBar) {
        setDefaultImmerBar();
    }

    @Override
    protected BaseIViewPresenter initBaseIViewPresenter() {
        return null;
    }

    @Override
    protected void init() {
        ARouter.getInstance().inject(this);
        CommonUtils.getInstance().putConfigData(AppConfigConstant.SHORT_VIDEO_STATE, "END");
        initView();
        getActivityIsFinsih();
    }

    @Override
    protected void setListener() {
    }

    private void initView() {
        BusFactory.getBus().register(this);
        if (Hawk.contains("login")) {
            String headicon = CommonUtils.getInstance().getUserLogo();
            Glide.with(this)
                    .load(headicon)
                    .apply(new RequestOptions().error(R.drawable.comment_head_default).placeholder(R.drawable.comment_head_default))
                    .into(userAvatar);
        }
        List<Fragment> fragmentList = new ArrayList<>();
        fragmentList.add(ShortVideoHomeFragment.newInstance(activityId));
        fragmentList.add(ShortVideoThemeFragment.newInstance(activityId));
        fragmentList.add(ShortVideoRankFragment.newInstance(activityId));
        fragmentList.add(ShortVideoIntroductionFragment.newInstance(activityId));
        viewPager.setAdapter(new Adapter(getSupportFragmentManager(), fragmentList, new String[]{"首页", "主题秀", "排行榜", "介绍"}));
        viewPager.setOffscreenPageLimit(3);
        tabLayout.setViewPager(viewPager);
    }

    @OnClick({R2.id.back_btn, R2.id.user_avatar, R2.id.search_btn, R2.id.shoot_btn})
    public void onViewClicked(View view) {
        int i = view.getId();
        if (i == R.id.back_btn) {
            finish();
        } else if (i == R.id.user_avatar) {

            CommonUtils.getInstance().isLogin(new UserService.LoginCallBack() {
                @Override
                public void login(boolean isLogin) {
                    if (isLogin) {
                        String userName = CommonUtils.getInstance().getUserName();
                        Bundle bundle = new Bundle();
                        bundle.putString("userName", userName);
                        bundle.putString("id", activityId);
                        RouterManager.router(ARouterPathConstant.SHORT_VIDEO_USER,bundle);

                    } else {
                        Toasty.normal(ShortVideoActivity.this, "尚未登录或登录已失效！").show();
                        RouterManager.routerLogin(ShortVideoActivity.this, 0);
                    }
                }

                @Override
                public void error(String s) {

                }
            });

        } else if (i == R.id.search_btn) {
            Bundle bundle =  new Bundle();
            bundle.putString("type", "all");
            bundle.putString("id", activityId);
            RouterManager.router(ARouterPathConstant.SHORT_VIDEO_SEARCH,bundle);

        } else if (i == R.id.shoot_btn) {
            String activityStatus = CommonUtils.getInstance().getShortVideoState();
            if (activityStatus.equals("BEGINNING")) {
                MPermissionUtils.requestPermissionsResult(ShortVideoActivity.this, 1, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.CAMERA, Manifest.permission.RECORD_AUDIO}, new MPermissionUtils.OnPermissionListener() {
                    @Override
                    public void onPermissionGranted() {
                        CommonUtils.getInstance().isLogin(new UserService.LoginCallBack() {
                            @Override
                            public void login(boolean isLogin) {
                                if (isLogin) {
                                    if (StringUtils.isMi8()) {
                                        Bundle bundle = new Bundle();
                                        bundle.putString("id", activityId);
                                        RouterManager.router(ARouterPathConstant.SHORT_VIDEO_SHOOT2,bundle);

                                    } else {
                                        Bundle bundle = new Bundle();
                                        bundle.putString("id", activityId);
                                        RouterManager.router(ARouterPathConstant.SHORT_VIDEO_SHOOT,bundle);
                                    }
                                } else {
                                    Toasty.normal(ShortVideoActivity.this, "尚未登录或登录已失效！").show();
                                    RouterManager.routerLogin(ShortVideoActivity.this, 0);
                                }
                            }

                            @Override
                            public void error(String s) {

                            }
                        });
                    }

                    @Override
                    public void onPermissionDenied() {
                        MPermissionUtils.showTipsDialog(ShortVideoActivity.this);
                    }
                });
            } else if (activityStatus.equals("END")) {
                showToast("活动已结束！", 4);
            } else {
                showToast("活动未开始！", 4);
            }
        }
    }

    class Adapter extends FragmentPagerAdapter {
        private List<Fragment> fragmentList;
        private String[] names;

        public Adapter(FragmentManager fm, List<Fragment> fragmentList, String[] names) {
            super(fm);
            this.fragmentList = fragmentList;
            this.names = names;
        }

        @Override
        public Fragment getItem(int position) {
            return fragmentList.get(position);
        }

        @Override
        public int getCount() {
            return fragmentList.size();
        }

        @Override
        public CharSequence getPageTitle(int position) {
            return names[position];
        }
    }

    /**
     * 通过滑动距离判断上滑还是下滑来展开收起拍摄按钮
     *
     * @param dy 滑动
     */
    public void showHideBottombar(int dy) {
        if (!isRunning) {
            if (dy > 10) {  //上滑
                if (bottomBarStatus == BottomBarStatus.EXPAND) {
                    bottomBarStatus = BottomBarStatus.COLLAPSED;
                    //执行收起
                    ViewCompat.animate(bottomBar)
                            .translationYBy(StringUtils.dip2px(this, 70))
                            .setDuration(300)
                            .setListener(new ViewPropertyAnimatorListener() {
                                @Override
                                public void onAnimationStart(View view) {
                                    isRunning = true;
                                }

                                @Override
                                public void onAnimationEnd(View view) {
                                    isRunning = false;
                                }

                                @Override
                                public void onAnimationCancel(View view) {

                                }
                            });
                }
            } else if (dy < -10) { //下拉
                if (bottomBarStatus == BottomBarStatus.COLLAPSED) {
                    bottomBarStatus = BottomBarStatus.EXPAND;
                    //执行展开
                    ViewCompat.animate(bottomBar)
                            .translationYBy(StringUtils.dip2px(this, -70))
                            .setDuration(300)
                            .setListener(new ViewPropertyAnimatorListener() {
                                @Override
                                public void onAnimationStart(View view) {
                                    isRunning = true;
                                }

                                @Override
                                public void onAnimationEnd(View view) {
                                    isRunning = false;
                                }

                                @Override
                                public void onAnimationCancel(View view) {

                                }
                            });
                }
            }
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        BusFactory.getBus().unregister(this);
    }



    @Subscribe(threadMode = ThreadMode.MAIN)
    public void getMessage(Event.LoginMessage event) {
        if (event != null) {
            if (event.isLogin()) {
                String headicon = CommonUtils.getInstance().getUserLogo();
                Glide.with(this)
                        .load(headicon)
                        .apply(new RequestOptions().error(R.drawable.comment_head_default).placeholder(R.drawable.comment_head_default))
                        .into(userAvatar);
            } else {
                userAvatar.setImageResource(R.drawable.comment_head_default);
            }
        }
    }


    private void getActivityIsFinsih() {


        EasyHttp.get(VideoUrl.GET_SHORT_VIDEO_IS_FININSH)
                .params("actId", activityId)
                .params("siteId", CommonUtils.getInstance().getSite()+"")
                .execute(new SimpleCallBack<String>() {
                    @Override
                    public void onError(ApiException e) {

                    }

                    @Override
                    public void onSuccess(String s) {
                        ApiResult result = new Gson().fromJson(s, ApiResult.class);
                        if (result.getCode() == 200) {
                            CommonUtils.getInstance().putConfigData(AppConfigConstant.SHORT_VIDEO_STATE, result.getData().toString());
                        } else {
                            CommonUtils.getInstance().putConfigData(AppConfigConstant.SHORT_VIDEO_STATE, "END");
                        }
                    }
                });
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        UMShareAPI.get(this).onActivityResult(requestCode, resultCode, data);
    }
}
